package com.xiangmo.travel.Service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiangmo.travel.Dto.ScoreDto;
import com.xiangmo.travel.Dvo.ScoreStatusDvo;
import com.xiangmo.travel.Entity.Score;
import com.xiangmo.travel.Service.ScoreService;
import com.xiangmo.travel.mapper.ScoreMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class ScoreServiceImpl implements ScoreService {
    @Autowired
    private ScoreMapper scoreMapper;

    @Override
    public Integer getStarNum(Long attractionsId, Long userId) {
        LambdaQueryWrapper<Score> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Score::getUserId, userId)
                        .eq(Score::getAttractionsId, attractionsId);
        Score score = new Score();
        score = scoreMapper.selectOne(lambdaQueryWrapper);
        return score != null ? score.getStarNum() : 0;
    }

    @Override
    public Integer setStarNum(Long attractionsId, Long userId, Integer starNum) {
        Score score = new Score();
        score.setStarNum(starNum);
        LambdaQueryWrapper<Score> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Score::getUserId, userId)
                .eq(Score::getAttractionsId, attractionsId);
        return scoreMapper.update(score, lambdaQueryWrapper);
    }

    @Override
    public Integer isStarNum(Long attractionsId, Long userId) {
        LambdaQueryWrapper<Score> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Score::getUserId, userId)
                .eq(Score::getAttractionsId, attractionsId);
        return scoreMapper.selectOne(lambdaQueryWrapper) == null ? 0 : 1;
    }

    @Override
    public Integer insertScore(ScoreDto scoreDto) {
        Score score = Score.builder()
                .starNum(scoreDto.getStarNum())
                .attractionsId(scoreDto.getAttractionsId())
                .userId(scoreDto.getUserId())
                .build();
        return scoreMapper.insert(score);
    }

    @Override
    public Long getScoreStar(Long attractionsId) {
        LambdaQueryWrapper<Score> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Score::getAttractionsId, attractionsId);
        Integer star = scoreMapper.getSumStarNum(attractionsId);
        Long num = scoreMapper.selectCount(lambdaQueryWrapper);
        if(star == null || num == 0){
            return 6L;
        }
        return star / num;
    }
}
